<template>
  <el-tabs
    v-model="activeName"
    class="icon-tabs px-[24px]"
    @tab-click="handleClick"
  >
    <el-tab-pane
      v-for="{ label, name } in tabs"
      :key="name"
      :label="label"
      :name="name"
    >
      <div v-if="!data.length">暂无数据</div>
      <IconGrids
        v-else
        :data="shownData"
        :selectedIcons="selectedIcons"
        @select="select"
      ></IconGrids>
    </el-tab-pane>
  </el-tabs>
</template>
<script lang="ts" setup>
import TinyPinyin from 'tiny-pinyin';
import { ref, watchEffect, computed } from 'vue';
import type { TabsPaneContext } from 'element-plus';
import { ElTabs, ElTabPane, ElMessage } from 'element-plus';
import IconGrids from './IconGrids.vue';
import iconWebApi from '../api/iconWeb';
import resourceApi from '../api/resource';
import dictApi from '../api/dict';
import { useIconListStore } from '../store';

const shownData = computed(() => {
  if (props.queryParam) {
    return data.value.filter((item) => {
      const name = TinyPinyin.convertToPinyin(item.name, '', true);

      return name.includes(props.queryParam.toLowerCase());
    });
  }
  return data.value;
});
const props = defineProps(['queryParam']);

const iconListStore = useIconListStore();

const selectedIcons = computed(() => {
  const obj = {};

  data.value.forEach((item) => {
    obj[item.id] = !!iconListStore.iconList.find(
      (icon) => icon.target === item.target
    );
  });
  return obj;
});

const tabs = ref([]);
const activeName = ref('');
function getIconType() {
  dictApi.getList().then((res) => {
    tabs.value = res.map((item) => ({
      label: item.dictLabel,
      name: item.dictValue,
    }));
    activeName.value = tabs.value[0] && tabs.value[0].name;
  });
}
getIconType();

const getData = () => {
  iconWebApi
    .getPage({
      current: 1,
      size: 300,
      type: activeName.value,
    })
    .then((res) => {
      data.value = res.records;
    });
};
const data = ref([]);
const handleClick = (tab: TabsPaneContext, event: Event) => {
  activeName.value = tab.paneName as string;
};

watchEffect(getData);

const emits = defineEmits(['select']);
const select = (icon) => {
  if (selectedIcons.value[icon.id]) {
    // 不能重复添加
    ElMessage({
      message: '本页面已添加，请切换到其他页面添加',
      type: 'warning',
    });
    return;
  }
  emits('select', icon);
};
</script>

<style lang="scss">
.icon-tabs {
  .el-tabs__nav-wrap:after {
    display: none;
  }
  .el-tabs__content {
    padding-bottom: 5px;
  }
}
</style>
